<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class MCreateFolderController
    extends MApplicationComponent 
    implements MIController
{
    public $_user_device_id = null;
    public $_user_id          = null;
    private $_init            = false;
    private $_parentFilePath  = null;
    
    public function invoke($uri=null)
    {
                                parent::init();
        $params = $_REQUEST;
                if (isset($params) === false || $params == null) {
            throw new MFileopsException(
                                        FXP::t('Bad Request'),
                                        MConst::HTTP_CODE_400);
        }
                        $user   = MUserManager::getInstance()->getCurrentUser();
        $device = MUserManager::getInstance()->getCurrentDevice();
        
        $this->_user_id           = $user->user_id;
        $this->_user_device_id    = $device->device_id;
        
                                $locale = "bytes";
        if (isset($params["locale"])) {
            $locale = $params["locale"];
        }
        if (isset($params["root"]) === false || isset($params["path"]) === false) {
            throw new MFileopsException(
                                        FXP::t('Bad Request'),
                                        MConst::HTTP_CODE_400);
        }
        $root = $params["root"];
        $path = $params["path"];
        $file_name          = MUtils::get_basename($path);
        if ($file_name === false)
        {
            throw new MFileopsException(
                                        FXP::t('file name is invalid'),
                                        MConst::HTTP_CODE_400);
        }
                                $is_invalid = MUtils::checkNameInvalid($file_name);
        if ($is_invalid)
        {
            FXP::log($path, MLogger::LEVEL_ERROR);
            throw new MFileopsException(
                                        FXP::t('Bad Request'),
                                        MConst::HTTP_CODE_400);
        }
                                $path           = MUtils::convertStandardPath($path);
        if ($path == false)
        {
            throw new MFileopsException(
                                        FXP::t('file name is invalid'),
                                        MConst::HTTP_CODE_400);
        }
        $path           = "/".$this->_user_id.$path;
                                $parent_path        = dirname($path);
        $query_db_file      = MFiles::queryAllFilesByPath($path);
        
                                $had_file_delete    = false;
        if (count($query_db_file) > 0)
        {
            if ($query_db_file[0]["is_deleted"] == false)
            {
                                throw new MFileopsException(
                                            FXP::t('already a folder at the given destination'),
                                            MConst::HTTP_CODE_403);
            }
            $had_file_delete = true;
        }
        $this->_parentFilePath = "/{$this->_user_id}";
                                $parent_file_id = $this->handlerParentFolder($parent_path);
        
        $file_detail = $this->createFile($path, $parent_file_id, $had_file_delete);

        $response                   = array();
        $response["size"]           = "0";
        $response["thumb_exists"]   = false;
        $response["bytes"]          = 0;
        $response["modified"]       = MUtils::formatIntTime($file_detail->file_update_time);
        
        $path                       = "{$this->_parentFilePath}/{$file_name}";
        $index                      = strlen("/{$this->_user_id}");
        $path                       = substr($path, $index);
        $response["path"]           = $path;
        $response["is_dir"]         = true;
        $response["icon"]           = "folder";
        $response["root"]           = $root;
        $response["revision"]       = 0;         echo json_encode($response);
    }
    
    
    public function handlerParentFolder($path)
    {
                                        if ($path == "\\" || $path == "/{$this->_user_id}" || $path == "/{$this->_user_id}/")
        {
            return 0;
        }
                                $query_db_file      = MFiles::queryAllFilesByPath($path);
        $had_file_delete    = false;
        if ($query_db_file)
        {
                                                if ($query_db_file[0]["file_type"] == MConst::OBJECT_TYPE_FILE)
            {
                throw new MFileopsException(
                                        FXP::t('parent folder cannot be file'),
                                        MConst::HTTP_CODE_500);
            }
                        if ($this->_init === false)
            {
                $this->_parentFilePath = $query_db_file[0]["file_path"];
                $this->_init = true;
            }
                                                if ($query_db_file[0]["is_deleted"] == false)
            {
                return $query_db_file[0]["id"];
            }
                        $had_file_delete = true;
        }
        
                                $parent_path = dirname($path);
                if ($this->_init === false)
        {
            $this->_parentFilePath = $path;
            $this->_init = true;
        }
        $parent_file_id = $this->handlerParentFolder($parent_path);
        $this->createFile($path, $parent_file_id, $had_file_delete);
        $query_db_file = MFiles::queryFilesByPath($path);
        if ($query_db_file === false || empty($query_db_file))
        {
            throw new MFileopsException(
                                        FXP::t('Internal Server Error'),
                                        MConst::HTTP_CODE_500);
        }
        return $query_db_file[0]["id"];
    }
    
    
    private function createFile($path, $parent_file_id, $had_file_delete)
    {
        $file_name = MUtils::get_basename($path);
                                $file_detail = new MFiles();
        $file_detail->file_create_time = time();
        $file_detail->file_update_time = time();
        $file_detail->file_name        = $file_name;
        $file_detail->file_path        = $path;
        $file_detail->file_size        = 0;
        $file_detail->file_type        = MConst::OBJECT_TYPE_DIRECTORY;
        $file_detail->parent_file_id   = $parent_file_id;
                                if ($had_file_delete)
        {
            $file_detail->event_uuid = MUtils::random_string(MConst::LEN_EVENT_UUID);
            $updates = array();
            $updates["file_update_time"]    = time();
            $updates["is_deleted"]          = intval(false);
            $updates["file_type"]           = MConst::OBJECT_TYPE_DIRECTORY;
            $updates["event_uuid"]          = $file_detail->event_uuid;
                        $ret_value = MFiles::updateFileDetailByPath($path, $updates);
        }
        else 
        {
                        $ret_value = MFiles::CreateFileDetail($file_detail, $this->_user_id);
        }
        if ($ret_value === false)
        {
            throw new MFileopsException(
                                        FXP::t('Internal Server Error'),
                                        MConst::HTTP_CODE_500);
        }
                                $event_action = MConst::CREATE_DIRECTORY;
        $ret_value = MEvents::CreateEvents($this->_user_id,
                                           $this->_user_device_id,
                                           $event_action,
                                           $file_detail->file_path,
                                           $file_detail->file_path,
                                           $file_detail->event_uuid
                                           );
        if ($ret_value === false)
        {
            throw new MFileopsException(
                                        FXP::t('already a folder at the given destination'),
                                        MConst::HTTP_CODE_500);
        }
        return $file_detail;
    }
}
?>